#!/bin/bash

# 备份脚本

BACKUP_DIR="/var/backups/web-notes"
DATE=$(date +%Y%m%d_%H%M%S)

echo "开始备份 Web Notes 应用..."

# 创建备份目录
mkdir -p $BACKUP_DIR

# 备份 MongoDB 数据
echo "备份数据库..."
mongodump --db web-notes-prod --out $BACKUP_DIR/mongodb_$DATE

# 备份上传文件
echo "备份上传文件..."
tar -czf $BACKUP_DIR/uploads_$DATE.tar.gz -C /var/www/web-notes/web-notes-backend uploads

# 备份配置文件
echo "备份配置文件..."
mkdir -p $BACKUP_DIR/config_$DATE
cp /var/www/web-notes/web-notes-backend/.env $BACKUP_DIR/config_$DATE/
cp /etc/nginx/conf.d/web-notes.conf $BACKUP_DIR/config_$DATE/
cp /var/www/web-notes/ecosystem.config.json $BACKUP_DIR/config_$DATE/

# 清理旧备份 (保留7天)
find $BACKUP_DIR -type d -name "*_*" -mtime +7 -exec rm -rf {} \;
find $BACKUP_DIR -name "*.tar.gz" -mtime +7 -delete

echo "备份完成: $BACKUP_DIR"
ls -la $BACKUP_DIR